import React from 'react'
import { Form, Input, Button, Space, Toast } from 'antd-mobile'


import MyHeader from '../../components/MyHeader'
import PassInput from '../../components/PassInput'
import { reg } from '../../utils/validate'
import { useRequest } from 'ahooks'
import { changeuserinfoAPI } from '../../api/api'
import { userInfoAction } from '../../hooks/userInfoAction'
import { ShowErrorMsg, ShowMsg } from '../../utils/message'
import { useNavigate, useSearchParams } from 'react-router-dom'

const ChangePass = () => {
  const router = useNavigate()
  const [form] = Form.useForm()
  const { todoLogout } = userInfoAction()
  const [query] = useSearchParams()

  // 更新密码请求
  const changePassAction = useRequest(changeuserinfoAPI, {
    manual: true,
    onSuccess: (res: any, params: any) => {
      if (res.code == 200) {
        ShowMsg('密码更改成功，请重新登录')
        todoLogout()
        router('/login')
      }
    }
  })

  // 校验三次密码逻辑
  const submitChange = () => {
    form.validateFields()
      .then(value => {
        if (query.get('password') != value.oldPass) {
          ShowMsg('旧密码不正确，请重新输入')
        } else {
          if (value.newPass == value.oldPass) {
            ShowMsg('新旧密码不能相同')
          } else {
            changePassAction.run({
              password: value.newPass
            })
          }
        }
      })
      .catch(err => {
        ShowErrorMsg('未知错误，请重试')
      })
  }

  return (
    <div>
      <MyHeader title='修 改 密 码'></MyHeader>

      <Form layout='horizontal' mode='card' form={form}>
        <Form.Header>请填写以下内容，以修改密码</Form.Header>
        <PassInput
          label='旧密码'
          name='oldPass'
        ></PassInput>
        <PassInput
          label='新密码'
          name='newPass'
          dependencies={['dbNewpass']}
        ></PassInput>
        <PassInput
          label='确认密码'
          name='dbNewPass'
          dependencies={['newPass']}
          rules={
            [
              ({ getFieldValue }) => ({
                validator(_: any, value: any) {
                  if (!value || !reg.pwd.test(value) || getFieldValue('newPass') === value) {
                    return Promise.resolve()
                  }
                  return Promise.reject(new Error('两次密码不一致'))
                }
              })
            ]
          }
        ></PassInput>
      </Form>

      <div style={{ width: '350px', margin: 'auto' }}>
        <Button color="success" className='mt20' block onClick={submitChange} >确 定</Button>
      </div>
    </div>
  )
}

export default ChangePass
